# -*- coding:utf-8 -*-

import pymysql
from .. import config
import markdown
import time
import json
from flask import render_template


def GetNowTime():
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))


def connectSQL():
    db = pymysql.connect(host=config.DatabaseIP,
                         port=config.Port,
                         user=config.UserName,
                         passwd=config.Password,
                         db=config.Database,
                         charset='utf8')
    return db


def SubmitData(data, ways):
    dbx = connectSQL()
    cursor = dbx.cursor()
    try:
        order = "SELECT MAX(id) FROM %s" % (data['type'])
        cursor.execute(order)
        datax = cursor.fetchall()
        if datax[0][0] is None:
            newid = 1
        else:
            newid = datax[0][0] + 1
        order = "INSERT INTO %s (id,title,summary,%s,time) VALUES (\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')" % (
            data['type'], ways, newid, data['title'], data['summary'], data['content'], str(GetNowTime()))
        cursor.execute(order)
        dbx.commit()
        dbx.close()
        return 1
    except:
        dbx.close()
        return 0


def SubmitMinder(data, type):
    dbx = connectSQL()
    cursor = dbx.cursor()

    try:

        order = "SELECT MAX(id) FROM %s" % (type)
        cursor.execute(order)
        datax = cursor.fetchall()
        if datax[0][0] is None:
            newid = 1
        else:
            newid = datax[0][0] + 1
        tmp = json.loads(data)

        f = render_template('api/minderFrame.html')
        tmpX = f

        htmltmp = tmpX % (newid, newid, data, newid)

        order = "INSERT INTO %s (id,title,summary,%s,time,content_html) VALUES (\'%s\',\'%s\',\'%s\',\'%s\',\'%s\',\'%s\')" % (
            type, "content_json", newid, tmp['root']['data']['text'], "Built by KityMinder", data, str(GetNowTime()),
            htmltmp)
        cursor.execute(order)

        dbx.commit()
        dbx.close()
        return 1

    except:
        dbx.close()
        return 0


def deHtml(lib):
    dbx = connectSQL()
    cursor = dbx.cursor()

    order = "SELECT id,content_md FROM %s WHERE content_html is NULL" % (lib);
    cursor.execute(order)
    data = cursor.fetchall()
    if data:
        for i in data:
            html = markdown.markdown(i[1])
            order = "UPDATE %s SET content_html = \'%s\' WHERE id = %s" % (lib, html, i[0])
            cursor.execute(order)
            dbx.commit()
    dbx.close()


def genHtml(lib):
    dbx = connectSQL()
    cursor = dbx.cursor()

    resTitle = []
    resContent = []
    res = []
    idlist = []
    order = "SELECT id FROM %s" % (lib)
    cursor.execute(order)
    data = cursor.fetchall()
    for i in data:
        idlist.append(i[0])
    for idx in idlist:
        order = "SELECT title FROM %s WHERE id = %s" % (lib, idx)
        cursor.execute(order)
        data = cursor.fetchall()
        if idx == 1:
            resTitle.append(
                '<a class=\"list-group-item list-group-item-action active\" id=\"list-%s-list\" data-toggle=\"list\" href=\"#list-%s\" role=\"tab\" aria-controls=\"%s\">%s</a>' % (
                    idx, idx, idx, data[0][0]))
        else:
            resTitle.append(
                '<a class=\"list-group-item list-group-item-action\" id=\"list-%s-list\" data-toggle=\"list\" href=\"#list-%s\" role=\"tab\" aria-controls=\"%s\">%s</a>' % (
                    idx, idx, idx, data[0][0]))

        order = "SELECT content_html FROM %s WHERE id = %s" % (lib, idx)
        cursor.execute(order)
        data = cursor.fetchall()
        if idx == 1:
            resContent.append(
                '<div class=\"tab-pane fade show active\" id=\"list-%s\" role=\"tabpanel\" aria-labelledby=\"list-%s-list\">%s</div>' % (
                    idx, idx, data[0][0]))
        else:
            resContent.append(
                '<div class=\"tab-pane fade\" id=\"list-%s\" role=\"tabpanel\" aria-labelledby=\"list-%s-list\">%s</div>' % (
                    idx, idx, data[0][0]))

    title = ''.join(resTitle)
    content = ''.join(resContent)

    res.append(title)
    res.append(content)
    dbx.close()
    return res
